package com.lanmaoly.cunzheng.queue.impl;

import com.lanmaoly.cunzheng.queue.Queue;

/**
 * 数组接口实现队列模型
 *
 * @author Administrator
 */
public class ArrayQueue<T> implements Queue<T> {

    public static void main(String[] args) {
        ArrayQueue<String> queue = new ArrayQueue<>(10);
        queue.enQueue("一号选手");
        queue.enQueue("二号选手");
        queue.enQueue("三号选手");

        int size = queue.size();
        System.out.println(size);
        for (int i = 0; i < size; i++) {
            if (queue.isEmpty()) {
                break;
            }
            System.out.println(i + ":" + queue.deQueue());
        }
    }

    /**
     * 队列首,之允许删除
     */
    private int front;
    /**
     * 队列尾,只允许添加
     */
    private int reer;
    /**
     * 最大长度
     */
    private int maxSize = 0;

    private Object[] data;

    public ArrayQueue(int maxSize) {
        front = reer = 0;
        this.maxSize = maxSize;
        this.data = new Object[maxSize];
    }

    @Override
    public int size() {
        return data.length;
    }

    @Override
    public boolean isEmpty() {
        return reer == front;
    }

    @Override
    public boolean enQueue(T t) {
        if (reer == maxSize) {
            throw new RuntimeException("队列满了---");
        } else {
            data[reer++] = t;
            return true;
        }
    }

    @Override
    public T deQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空---");
        } else {
            // 取出数据的同时将此位置数据置空再++
            T t = (T) data[front];
            data[front++] = null;
            return t;
        }
    }
}
